package com.zxtech.zzm.zxmonitorsocket.thread

import com.zxtech.zzm.core.util.HexUtil
import com.zxtech.zzm.zxmonitorsocket.resolver.SocketBaseResolver
import com.zxtech.zzm.zxmonitorsocket.util.SocketLoggerUtil
import java.io.IOException
import java.io.InputStream
import java.net.Socket

/**
 * Created by zheming.zou on 2017/2/7.
 */
class ResponseThread(s: Socket) : Thread() {
  private val s: Socket?
  private var clientis: InputStream? = null
  @Volatile private var stopflag = true //true 线程停止， false线程继续
  fun setStopFlag(stopFlag: Boolean) {
    stopflag = stopFlag
  }

  override fun run() {
    this.name = "zxmonitor_socket_response"
    SocketLoggerUtil.logSocket("线程" + this.id + "听包线程开始")
    super.run()
    stopflag = false
    var len = 0
    val buffer = ByteArray(1024)
    try {
      while (s != null && s.isConnected
          && !s.isClosed
          && !stopflag
          && clientis!!.read(buffer)
              .also { len = it } != -1
      ) {
        var responseData: String
        if (len > 0) {
          responseData = HexUtil.encodeHexStr(buffer)
              .substring(0, len * 2)
          SocketBaseResolver.getIns().resolve(responseData)
        }
      }
    } catch (e: IOException) {
      e.printStackTrace()
    }
    SocketLoggerUtil.logSocket("线程" + this.id + "听包线程终止")
    interrupt()
  }

  init {
    this.s = s
    try {
      clientis = s.getInputStream()
    } catch (e: IOException) {
      e.printStackTrace()
    }
  }
}